--local Piece = require "packages.hearthstone.battlegrounds.core.piece"

---@class Battlegrounds.Engine : Base.Engine
---@field public pieces table<integer, Battlegrounds.Piece>
local Engine = Fk.Base.Engine:subclass("Battlegrounds.Engine")

-- 全是写死棋子坐标和id的，过于繁冗，折叠起来


function Engine:initialize()
  Fk.Base.Engine.initialize(self)

  self.pieces = {}
end

function Engine:addPiece(piece)
  self.pieces[piece.id] = piece
end

---@param id integer
---@return Xiangqi.Piece
function Engine:getPieceById(id)
  return self.pieces[id]
end

---@return integer[][]
function Engine:createBoard()
  -- 创建空棋盘
  local board = {
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    -- ↑黑方 楚河汉界 红方↓
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
    {0, 0, 0, 0, 0, 0, 0, 0, 0},
  }

  -- 遍历32颗棋子，根据 initialPositions 写回初始坐标
  for id, pos in pairs(self.initialPositions) do
    board[pos.y][pos.x] = id
  end

  return board
end

--加载商店
function Engine:loadShop()
  self.shop = {}
end



function Engine:translateMovement(pieceId, board, fromX, fromY, x, y)
  local piece = self:getPieceById(pieceId)
  local color = piece:getColor()

  local pieceName = ('<font color="%s">%s</font>'):format(color, color == "red" and piece.redStr or piece.blackStr)
  local fromLine = self:getLineNumber(fromX, color)

  -- 判这列是否还有自己的
  for _y = 1, 10 do
    if _y ~= fromY then
      local p = self:getPieceById(board[_y][fromX])
      if p and p.name == piece.name and p:getColor() == color then
        -- 若在自己前进方向发现有其他棋子则。。
        if (color == "red" and _y < fromY) or
          (color == "black" and _y > fromY) then
          pieceName = "后" .. pieceName
        else
          pieceName = "前" .. pieceName
        end

        fromLine = ""
        break
      end
    end
  end

  -- 判断移动方向
  local direction, target
  if fromY == y then -- 横向移动
    direction = "平"
    target = self:getLineNumber(x, color)
  else
    if (color == "red" and y < fromY) or
      (color == "black" and y > fromY) then
      direction = "进"
    else
      direction = "退"
    end

    if piece.name == "knight" or
      piece.name == "advisor" or
      piece.name == "bishop" then
      target = self:getLineNumber(x, color)
    else
      if color == "red" then
        target = self.ChineseNumbers[math.abs(y - fromY)]
      else
        target = self.ArabicNumbers[math.abs(y - fromY)]
      end
    end
  end

  return pieceName .. fromLine .. direction .. target
end

return Engine
